package com.atguigu.self.common.valid;

import com.atguigu.self.common.valid.annotation.ListValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author Li Xinyang  <lixinyang@xxx.com>  2021/2/1 8:17
 **/
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {


    private Set<Integer> initVals = new HashSet<>();

    /**
     * 拿到注解的详细信息（参数值）
     *
     * @param constraintAnnotation 拿到注解的详细信息（参数值）
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals = constraintAnnotation.vals();
        for (int val : vals) {
            initVals.add(val);
        }

    }

    /**
     * 自定义校验规则
     *
     * @param value   object to validate， 当前请求传过来的属性值
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (initVals.contains(value)) {
            return true;
        }
        return false;
    }
}
